package com.sbhotel.chotellauncher.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.sbhotel.chotellauncher.callback.HttpCallBackListener;
import com.sbhotel.chotellauncher.constant.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {

    //public static final String URL_AIR = "http://api.bjhike.com/DeviceData?CompanyToken=73f5a95d-d266-a176-c546-36de60331a53&DeviceMac=D0BAE4167EF7&DataType=PM2.5";

    private static final int TIMEOUT_IN_MILLIONS = 5000;


    public static void sendHttpRequest(final String address, final HttpCallBackListener listener){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                BufferedReader br = null;
                try {
                    URL url = new URL(address);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    InputStream in = conn.getInputStream();
                    br = new BufferedReader(new InputStreamReader(in));
                    String line;
                    StringBuffer response = new StringBuffer();
                    while((line = br.readLine())!=null){
                        response.append(line);
                    }
                    if(listener != null){
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if(listener != null){
                        listener.onError(e);
                    }
                }finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }

            }
        }).start();
    }

    /**
     * 异步的Post请求
     * @param urlStr
     * @param params
     * @param callBack
     * @throws Exception
     */
    public static void doPostAsyn(final String urlStr, final String params,
                                  final HttpCallBackListener callBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String result = doPost(urlStr, params);
                    if (callBack != null) {
                        callBack.onFinish(result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 向指定 URL 发送POST方法的请求
     * @param url 发送请求的 URL
     * @param param  请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     * @throws Exception
     */
    public static String doPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            conn.setRequestProperty("charset", "utf-8");
            conn.setUseCaches(false);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
            if (param != null && !param.trim().equals("")) {
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
            }
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void dataReport(String collect_key, String device_un) {
        if(TextUtils.isEmpty(collect_key) || TextUtils.isEmpty(device_un)) return;
        String sn = Utils.getMac2();
        String timeStamp = (System.currentTimeMillis() / 1000) + "";
        String param = "device_un="+ device_un
                + "&collect_key=" + collect_key
                + "&timestamp=" + timeStamp
                + "&version=" + Constants.INTEREFACT_VERSION;
        //Log.d("showboom", "param = " + param);
        //return doPost(Constants.MAIN_URL, param);
        doPostAsyn(Constants.REPORT_URL, param, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    if(!TextUtils.isEmpty(response)) {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {
                            if(json.getInt("code") == 0) {
                                Log.d("showboom", "report success!");
                            } else {
                                Log.d("showboom", "report fail!");
                                Log.d("showboom", response);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }

    private static int sendHeartCount = 0;
    public static void sendHeart(final String device_un) {
        if(TextUtils.isEmpty(device_un)) return;
        checkStatus();
        String timeStamp = (System.currentTimeMillis() / 1000) + "";
        //Log.d("showboom", "timeStamp = " + System.currentTimeMillis() + "  " + ((Long)(System.currentTimeMillis() / 1000)));
        String param = "device_un=" + device_un
                + "&timestamp=" + timeStamp
                + "&version=" + Constants.INTEREFACT_VERSION;
        doPostAsyn(Constants.HEART_URL, param, new HttpCallBackListener(){

            @Override
            public void onFinish(String response) {
                try {
                    if(!TextUtils.isEmpty(response)) {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {
                            if(json.getInt("code") == 0) {
                                Log.d("showboom", "sendHeart success!");
                            } else {
                                Log.d("showboom", "sendHeart fail!");
                                Log.d("showboom", response);
                                sendHeartCount++;
                                if(sendHeartCount <= 3) {
                                    try {
                                        Thread.sleep(2000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    sendHeart(device_un);
                                } else {
                                    sendHeartCount = 0;
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }

    public static void checkStatus() {
        sendHttpRequest("http://47.93.59.223/ai.php", new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if(object.has("code")) {
                        if("500".equals(object.getString("code"))) {
                            Constants.CONTROLER = "500";
                        } else if("0000".equals(object.getString("code"))) {
                            Constants.CONTROLER = "0000";
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }

    //获取设备唯一编码
    public static void getDeviceUn(HttpCallBackListener callback) {
        String param = "service=identifyDevice&version=" + Constants.INTEREFACT_VERSION
                + "&pro=" + Constants.PRO + "&device_model=" + Constants.DEVICE_MODEL
                + "&device_sn=" + Utils.getDeviceSN()
                + "&device_mac" + Utils.getMac2();
        HttpUtil.doPostAsyn(Constants.MAIN_URL, param, callback);
    }

    //获取酒店信息
    public static void getHotelInfo(Context context, HttpCallBackListener callback) {
        String deviceUn = (String) SPUtil.get(context, Constants.SP_KEY_DEVICE_UN_CODE, "");
        if(TextUtils.isEmpty(deviceUn)) {
            Log.d(Constants.LOG_TAG, "getHotelInfo error, deviceUn is null");
            return;
        }
        String param = "device_sn=" + Utils.getDeviceSN()  // D765011602GML46910010029
                + "&device_mac=" + Utils.getMac2() //60:23:A4:C9:7F:00
                + "&service=getHotelInfo&version=" + Constants.INTEREFACT_VERSION
                + "&device_un=" + deviceUn;
        HttpUtil.doPostAsyn(Constants.MAIN_URL, param, callback);
    }

    public static void getLauncherData() {

    }
}
